package pl.edu.mimuw.mas.utils;

import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.wrapper.AgentContainer;
import jade.wrapper.AgentController;
import jade.wrapper.ControllerException;
import jade.wrapper.StaleProxyException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Narzędzie do uruchamiania agentów na lokalnej maszynie z domyślnymi
 * ustawieniami.
 */
public final class JadeRunner {

	public static final String LOCAL_HOST = "localhost";
	public static final String LOCAL_PORT = "1099";
	
	private static AgentContainer cc = null;
	private static boolean running = false;
	
	private static Logger logger = LoggerFactory.getLogger(JadeRunner.class);
		
	public static boolean runLocalJade() {
		if(cc == null) {
			Profile p = new ProfileImpl();
			p.setParameter(Profile.MAIN_HOST, LOCAL_HOST);
			p.setParameter(Profile.MAIN_PORT, LOCAL_PORT);
			
			jade.core.Runtime rt = jade.core.Runtime.instance();
			cc = rt.createMainContainer(p);		
		}

		if (!running) {
			try {
				cc.start();
				running = true;
			} catch (ControllerException e) {
				logger.error("Niemożna uruchomić Jade", e);
				cc = null;
			}
		}
		
		return running;
	}
	
	public static void stopLocalJade() {
		if (running) {
			running = false;
			try {
				cc.kill();
			} catch (StaleProxyException e) {
				logger.error("Nieaktualne proxy", e);
			}
		}
	}
	
	public static boolean runAgent(String name, String className, Object[] params) {
		if(running) {
			try {
				AgentController ac;
				ac = cc.createNewAgent(name, className, params);
				ac.start();
				
				return true;
			} catch (StaleProxyException e) {
				logger.error("Nieaktualne proxy", e);
			}
		}
		return false;		
	}
	
	private JadeRunner() {	}
}
